package com.bgba.oer;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.rpc.ServiceException;

import com.bgba.oer.service.AssetSystemService;
import com.bgba.oer.service.ContactService;
import com.bgba.oer.service.RegistryUserService;
import com.bgba.oer.sharepoint.RequirementSharepoint;
import com.bgba.oer.sharepoint.SystemSharepoint;
import com.flashline.registry.openapi.base.APIValidationException;
import com.flashline.registry.openapi.base.OpenAPIException;
import com.flashline.registry.openapi.entity.AuthToken;
import com.flashline.registry.openapi.entity.Asset;
import com.flashline.registry.openapi.entity.Contact;
import com.flashline.registry.openapi.entity.Extraction;
import com.flashline.registry.openapi.entity.Project;
import com.flashline.registry.openapi.entity.ProjectEntities;
import com.flashline.registry.openapi.entity.RegistryUser;
import com.flashline.registry.openapi.query.ProjectCriteria;
import com.flashline.registry.openapi.service.v300.FlashlineRegistry;
import
com.flashline.registry.openapi.service.v300.FlashlineRegistryServiceLocator;
public class SystemImporter {

	public static void main(String pArgs[]) throws ServiceException, ParserConfigurationException, SAXException, IOException  {

		System.out.println("======================== ");
		String urlConnectionLogin = "http://desasoa01/oer/services/FlashlineRegistry?WSDL";
		String username = " L0269239";
		String password = "finde2011";
		/*
		String urlConnectionLogin = "http://172.17.1.10:8101/oer/services/FlashlineRegistry?WSDL";
		String username = " admin";
		String password = "admin123";
		 */
		///////////////////////////////////////////////////////////
		// Connect to Oracle Enterprise Repository
		///////////////////////////////////////////////////////////
		URL lURL = null;
		lURL = new URL(urlConnectionLogin);
		FlashlineRegistry repository = new FlashlineRegistryServiceLocator().getFlashlineRegistry(lURL);

		///////////////////////////////////
		// Login to OER
		///////////////////////////////////
		AuthToken authToken = repository.authTokenCreate(username, password);


		////////////////////////////////////////////////////////
		// Parse XML de Sistemas exportado de SharePoint
		////////////////////////////////////////////////////////

		List<SystemSharepoint> systemsSharepointList = parseSystemXml();

		for (SystemSharepoint  systemSharepoint : systemsSharepointList) {
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("============== SystemSharepoint ID ="+systemSharepoint.getId());
			System.out.println("============== SystemSharepoint Title ="+systemSharepoint.getTitle());
			
			Asset systemAsset = new Asset();
			systemAsset.setName(systemSharepoint.getTitle());
			systemAsset.setVersion("1.0");
			
			Asset newSystemAsset = AssetSystemService.addSystemAsset(repository, authToken, systemAsset);

			if (systemSharepoint.getResponsibles() != null || systemSharepoint.getResponsibles().size() > 0) {
				Contact[] contactsForSystemAsset = new Contact[systemSharepoint.getResponsibles().size()];
				int contactIndex = 0;

				for (String responsibleSharepoint : systemSharepoint.getResponsibles()) {
					// buscamos el usuario para poder buscar el contacto, el contacto se busca solo por el "Apellido" + "Nombre" 
					RegistryUser registryUserOer = RegistryUserService.searchRegistryUser(repository, authToken, responsibleSharepoint);

					if (registryUserOer == null){
						System.out.println("============= ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!!");
						System.out.println("============= ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!!");
						System.out.println("============= ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!! ERROR !!!");
						System.out.println("============= NOT FOUND registryUser for responsible="+responsibleSharepoint+ ", systemSharepoint.getId="+systemSharepoint.getId());
						//break;
						registryUserOer = RegistryUserService.searchRegistryUser(repository, authToken, "admin");
						
						//String[] messageArgs = {"NOT FOUND registryUser for responsible="+responsibleSharepoint};
						//throw new OpenAPIException(messageArgs, 1, "", "", "ERROR" );							
					}
					System.out.println("============== registryUserOer.getID="+registryUserOer.getID());
					System.out.println("============== registryUserOer.getDisplayName="+registryUserOer.getLastName()+", "+registryUserOer.getFirstName());
					System.out.println("============== registryUserOer.getEmail="+registryUserOer.getEmail());
					
					// buscamos si el contacto ya existe en la DB
					Contact contactOer = ContactService.searchContactByName(repository, authToken, registryUserOer.getLastName()+", "+registryUserOer.getFirstName());

					if (contactOer == null){
						System.out.println("============= NOT FOUND contact for responsible="+responsibleSharepoint);
						
						// aqui se debe crear el contacto y luego agregarlo
						// posiblemente se debe persitir el contacto y luego agregarlo al array de contacto 
						contactOer = new Contact();
						contactOer.setName(registryUserOer.getLastName()+ ", "+ registryUserOer.getFirstName());
						contactOer.setEmail(registryUserOer.getEmail());
						contactOer.setPhoneNumber(registryUserOer.getPhoneNumber());
						
						contactOer = ContactService.addContact(repository, authToken, contactOer);
						System.out.println("============= contactOer.getID=="+contactOer.getID());	
					}
					// aqui hay que agregar el contacto ya existente al array
					
					contactsForSystemAsset[contactIndex] = contactOer;
					contactIndex ++;
					System.out.println("============= added contact ID=="+contactOer.getID());	
				}
				
				System.out.println("=================== Se van a agregar los contactos para el asset, total de contactos=" + contactsForSystemAsset.length);
				newSystemAsset.setContacts(contactsForSystemAsset);
				// si se llego hasta aqui, es xq ya se agregaron los contacts al array
				// ahora hay que hacer un update del asset
				newSystemAsset =  repository.assetUpdate(authToken, newSystemAsset);

				System.out.println("======== Se hizo el update Final del asset System id="+newSystemAsset.getID());

			} else {
				System.out.println("======== systemSharepoint.getTitle="+systemSharepoint.getTitle()+", has not responsibles");
			}
		}
		
		/*
		for (SystemSharepoint systemsSharepointList : systemSharepoint) {
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("===== req ID ="+requirementSharepoint.getId());
			System.out.println("===== req Number ="+requirementSharepoint.getNumber());
			System.out.println("===== req Name ="+requirementSharepoint.getName());
			System.out.println("===== req UserId ="+requirementSharepoint.getUserId());

			Project oerProject = new Project();
			oerProject.setName(requirementSharepoint.getNumber() + " - "+ requirementSharepoint.getName());
			oerProject.setDisplayName(requirementSharepoint.getName());
			oerProject.setDescription(requirementSharepoint.getName());

			long registryUserOerId = 0;
			if (requirementSharepoint.getUserId() > 0){ 

				String usernameOer = ResourceBundleHelper.getInstance().getSharePointUserName(String.valueOf(requirementSharepoint.getUserId()));				
				System.out.println("==== usernameOer="+usernameOer);

				RegistryUser registryUserOer = RegistryUserService.searchRegistryUser(repository, authToken, usernameOer);
				System.out.println("============ registryUserOer.getID="+registryUserOer.getID());
				System.out.println("============ registryUserOer.getEmail="+registryUserOer.getEmail());

				registryUserOerId = registryUserOer.getID();
			}

			ProjectService.addProject(repository, authToken, oerProject, registryUserOerId);
			System.out.println("============ #################################### ###############################");
			System.out.println("============ #################################### SE HA CREADO UN PROJECT");
			System.out.println("============ #################################### ###############################");


		}
		 */

		/*
		Project myProject = new Project();
		//myProject.setName("NEW_PROJECT_NAME");
		//myProject.setDisplayName("The New Proyect Name");

		ProjectService.addProject(repository, authToken, myProject, 111111111);
		 */

	}


	public static List<SystemSharepoint>  parseSystemXml() throws ParserConfigurationException, SAXException, IOException {


		// lista de sistemas de Sharepoint
		List<SystemSharepoint> systemsList = new ArrayList<SystemSharepoint>();

		File file = new File("/home/alex/galicia/oer_migracion/OER/Sistemas.xml");
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(file);
		doc.getDocumentElement().normalize();
		System.out.println("Root element " + doc.getDocumentElement().getNodeName());
		NodeList nodeLst = doc.getElementsByTagName("Sistemas");
		System.out.println("Sistemas");

		for (int s = 0; s < nodeLst.getLength(); s++) {

			Node fstNode = nodeLst.item(s);

			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

				Element fstElmnt = (Element) fstNode;
				NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("ID");
				Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
				//System.out.println("== fstNmElmnt.getTagName="+fstNmElmnt.getTagName());
				NodeList fstNm = fstNmElmnt.getChildNodes();
				String sisteIdString =  ((Node) fstNm.item(0)).getNodeValue();
				System.out.println("\nSistem ID: "+sisteIdString);  

				NodeList fstNmElmntLstTitulo= fstElmnt.getElementsByTagName("Título");
				Element fstNmElmntTitulo = (Element) fstNmElmntLstTitulo.item(0);
				//System.out.println("== fstNmElmntTitulo.getTagName="+fstNmElmntTitulo.getTagName());
				NodeList fstNmTitulo = fstNmElmntTitulo.getChildNodes();
				String sisteTitulo = ((Node) fstNmTitulo.item(0)).getNodeValue();
				System.out.println("Titulo: " + sisteTitulo);

				NodeList fstNmElmntLstResponsable = fstElmnt.getElementsByTagName("Responsable");
				Element fstNmElmntResponsable = (Element) fstNmElmntLstResponsable.item(0);
				//System.out.println("== fstNmElmnt.getTagName="+fstNmElmntResponsable.getTagName());
				NodeList fstNmResponsable = fstNmElmntResponsable.getChildNodes();
				String sisteResponsable = ((Node) fstNmResponsable.item(0)).getNodeValue();
				System.out.println("Responsable: " + sisteResponsable);

				/*
					NodeList fstNmElmntLstResp = fstElmnt.getElementsByTagName("Responsable");
					//System.out.println("=== fstNmElmntLstResp Respon"+ fstNmElmntLstResp);
					NodeList fstNmElmntLstRespValue = fstElmnt.getElementsByTagName("Value");
					Element fstNmElmntRespValue = (Element) fstNmElmntLstRespValue.item(0);
					//System.out.println("=== fstNmElmntRespValue ="+fstNmElmntRespValue);
					String requiUserSharePointIdString = "0";
					if (fstNmElmntRespValue != null){
						//System.out.println("== fstNmElmnt.getTagName="+fstNmElmntRespValue.getTagName());
						NodeList fstNmRespValue = fstNmElmntRespValue.getChildNodes();
						requiUserSharePointIdString = ((Node) fstNmRespValue.item(0)).getNodeValue();
					}
					System.out.println("Responsable Value ID: "  + requiUserSharePointIdString);
				 */

				/*
					NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Responsable");
					Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
					NodeList lstNm = lstNmElmnt.getChildNodes();
					System.out.println("Estado : " + ((Node) lstNm.item(0)).getNodeValue());
				 */

				int sysId = Integer.parseInt(sisteIdString);
				SystemSharepoint systemSharepoint = new SystemSharepoint(sysId, sisteTitulo);

				String[] responsibles = sisteResponsable.split("/");
				for (String responsible : responsibles) {
					System.out.println("===== Sharepoint - Sistema.responsable="+responsible.trim());
					systemSharepoint.addResponsible(responsible.trim());
				}
				
				systemsList.add(systemSharepoint);

			}
		}

		return systemsList;
	}



}
